﻿using System;
using System.Data.SqlClient;
using System.IO;

namespace Business
{
    public class LogRepository : BaseBusiness
    {
        public void ClearAll()
        {
            DB.ExecuteCommand("TRUNCATE TABLE crm_log");
            DB.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, DB.crm_logs);
        }

        public void InsertLog(Exception e)
        {
            try
            {
                Console.WriteLine(e);
                using (SqlConnection conn = new SqlConnection(Settings.LocalSettings.ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "INSERT INTO crm_log(log_message, log_source, log_stack_trace, log_time, enabled) \n" +
                                          "VALUES(@log_message, @log_source, @log_stack_trace, @log_time, @enabled)";
                        cmd.CommandType = System.Data.CommandType.Text;
                        cmd.Parameters.AddWithValue("@log_message", e.Message);
                        cmd.Parameters.AddWithValue("@log_source", e.Source);
                        cmd.Parameters.AddWithValue("@log_stack_trace", e.StackTrace);
                        cmd.Parameters.AddWithValue("@log_time", DateTime.Now);
                        cmd.Parameters.AddWithValue("@enabled", true);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    Console.WriteLine(ex.Message);
                    string errmesage = "//////////////////////////////////////////\n" +
                                       "////////////////" + DateTime.Now + "/////////\n" +
                                       "log_mesage:      " + ex.Message + "\n" +
                                       "log_source:      " + ex.Source + "\n" +
                                       "log_stack_trace: " + ex.StackTrace + "\n" +
                                       "enabled:          true";
                    using (StreamWriter writer = new StreamWriter(Path.Combine(Environment.CurrentDirectory, LogFileNam()),
                        true))
                    {
                        writer.WriteLine(errmesage);
                    }
                }
                catch (Exception cath)
                {
                    Console.WriteLine(cath.Message);
                }
            }
        }

        string LogFileNam()
        {
            return string.Format("crm_log_{0}{1}{2}.txt", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        }
    }
}
